/* 
 * Copyright (c)	Insighten Intelligent Equipment co.,LTD
 * 
 *  Use of this software is controlled by the terms and conditions found
 *  in the license agreement under which this software has been supplied.
 * 
 */
/** 
 * @file msg_thread.c
 * @brief message process thread 
 * @author taco [tacoee@gmail.com]
 * @version 0.1
 * @date 2010-09-13
 */
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#include "message.h"

Message *msg_create(int key, int priv_msg_size)
{
	Message *thiz = NULL;

	thiz = calloc(sizeof(Message) + priv_msg_size, 1);
	if (thiz != NULL) {
		thiz->qid = msgget(key, IPC_CREAT | 0666);
		if (thiz->qid < 0) {
			thiz->qid = msgget(key, 0);
		}
		if (thiz->qid < 0) {
			return NULL;
		}
		thiz->key = key;
		thiz->msg_t_len = priv_msg_size;
	}

	return thiz;
}

Ret msg_destory(Message *thiz)
{
	if (thiz != NULL) {
		free(thiz);
		return RET_OK;
	}

	return RET_FAIL;
}
Ret msg_destory_deeply(Message *thiz)
{
	return_val_if_fail(thiz != NULL, RET_FAIL);
	
	if (msgctl(thiz->qid, IPC_RMID, NULL) < 0){
		return RET_FAIL;
	}
	free(thiz);
	thiz = NULL;

	return RET_OK;
}
int msg_send(Message *thiz)
{
	return_val_if_fail(thiz != NULL, -1);

	return msgsnd(thiz->qid, thiz->msg_t, thiz->msg_t_len-sizeof(long), 0);
}

int msg_rcv(Message *thiz, long mtype)
{
	return_val_if_fail(thiz != NULL, -1);

	return msgrcv(thiz->qid, thiz->msg_t, thiz->msg_t_len - sizeof(long), mtype, 0);
}
